#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpSocket>
#include <QDataStream>

QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_connectButton_clicked();
    void on_disconnectButton_clicked();
    void on_readCoilsButton_clicked();
    void on_readInputsButton_clicked();
    void on_readHoldingRegsButton_clicked();
    void on_readInputRegsButton_clicked();
    void on_writeCoilButton_clicked();
    void on_writeRegButton_clicked();

    void onSocketStateChanged(QAbstractSocket::SocketState state);
    void onSocketError(QAbstractSocket::SocketError error);
    void onSocketReadyRead();

private:
    Ui::MainWindow *ui;
    QTcpSocket *m_socket;
    quint16 m_transactionId;

    QByteArray createModbusRequest(quint8 functionCode, quint16 startAddress, quint16 count);
    QByteArray createWriteCoilRequest(quint16 address, bool value);
    QByteArray createWriteRegisterRequest(quint16 address, quint16 value);
    void parseModbusResponse(const QByteArray &response);
    void sendRequest(const QByteArray &request);
    void updateUiState();
};

#endif // MAINWINDOW_H
